package com.gmics.unifiq.menu;

import java.util.ArrayList;
import java.util.HashMap;

import com.gmics.android.R;
import com.gmics.unifiq.Planner;
import com.gmics.unifiq.ViewEvent;
import com.gmics.unifiq.adapter.AvatarAdapter;
import com.gmics.unifiq.controller.EntityController;
import com.gmics.unifiq.controller.UserFunctions;
import com.gmics.unifiq.entity.Avatar;
import com.gmics.unifiq.entity.CheckIn;
import com.gmics.unifiq.entity.User;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class ChangeAvatar extends Activity {
	private EntityController controller = new EntityController();
	private GridView avatarGV;
	private Avatar avatar, selectedAvatar;
	private User user;
	private ProgressDialog pDialog = null;
	private ArrayList<Avatar> avatarArr = new ArrayList<Avatar>();
	private int result = 0;
	private AvatarAdapter avatarAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.change_avatar_layout);
		
	    if (android.os.Build.VERSION.SDK_INT > 9) {
	        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	        StrictMode.setThreadPolicy(policy);
	      }
	    
	    try{
		    Bundle b = getIntent().getExtras();
		    user = (User) b.getSerializable("user");
		    avatar = (Avatar) b.getSerializable("avatar");
	    }
	    catch (Exception ex){
			UserFunctions uf = new UserFunctions();
			HashMap<String, String> mapUser = uf.getUser(this);
			user = controller.retrieveUser(mapUser.get("uid"));
			avatar = controller.retrieveAvatar(user.getAvatarID());
	    }
	    
	    new LoadAvatar().execute();

	}

    class LoadAvatar extends AsyncTask<String, String, String> {
   	 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ChangeAvatar.this);
            pDialog.setMessage("Loading avatars...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 

        protected String doInBackground(String... args) {
    		UserFunctions uf = new UserFunctions();
    		HashMap<String, String> user = uf.getUser(ChangeAvatar.this);
    		User tempUser = controller.retrieveUser(user.get("uid"));
    		int userID = tempUser.getId();
    		
        	ArrayList<CheckIn> checkInArr = controller.retrieveCheckIn(userID);
        	
    	    avatarArr = controller.retrieveAvatarFilter(checkInArr.size());
    	    avatarAdapter = new AvatarAdapter(ChangeAvatar.this, avatarArr);
            return null;
        } 
 
        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
            	    avatarGV = (GridView) findViewById(R.id.change_avatar_gv);         	     
            	    avatarGV.setAdapter(avatarAdapter);
            	    avatarGV.setOnItemClickListener(new OnItemClickListener(){

            			@Override
            			public void onItemClick(AdapterView<?> av, View v, int pos,
            					long id) {
            				// TODO Auto-generated method stub
            				selectedAvatar = (Avatar) avatarAdapter.getItem(pos);
            				if (avatar.getId() != selectedAvatar.getId()){
            					String msg = "";
            					
            					if (controller.updateUserAvatar(user.getId(), selectedAvatar.getId())){
            						msg = selectedAvatar.getName() + " selected! It is now your new avatar.";
            						result = RESULT_OK;
            					}
            					else{
            						msg = "Avatar not successfully selected. Please try again.";
            					}
            					
            					Toast.makeText(ChangeAvatar.this, msg, Toast.LENGTH_LONG).show();
            				}
            			}
            	    	
            	    });
                }
            });
            
        }
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public void onBackPressed() {
		Intent accountScreen = new Intent(this, Account.class);
		if (result == RESULT_OK){
			Bundle b = new Bundle();
			b.putSerializable("updatedAvatar", selectedAvatar);
			accountScreen.putExtras(b);
		}
		setResult(result, accountScreen);

		super.onBackPressed();
	}

}
